package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.Result;
import com.example.entity.SBrand;
import com.example.service.SBrandService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/brands")
public class SBrandController {
    @Autowired
    private SBrandService brandService;

    @ApiOperation("新增品牌")
    @PostMapping("/add")
    public Result<?> addBrand(@RequestBody SBrand brand){

        brandService.save(brand);
        return Result.success();
    }

    @ApiOperation("单选/多选删除品牌")
    @DeleteMapping("/delete")
    public Result<?> deleteBrands(@RequestBody List<Long> list){
        brandService.removeBatchByIds(list);
        return Result.success();
    }



    @ApiOperation("更新品牌信息")
    @PostMapping("/update")
    public Result<?> updateBrand(@RequestBody SBrand sBrand){
        LambdaQueryWrapper<SBrand> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SBrand::getId,sBrand.getId());
        brandService.update(sBrand,wrapper);
        return Result.success();
    }


    @ApiOperation("查看品牌，可根据名字模糊查询")
    @GetMapping("/get")
    public Result<List<SBrand>> selectBrand(@RequestParam(required = false, defaultValue = "") String name){
        LambdaQueryWrapper<SBrand> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name!=null,SBrand::getName,name);
        List<SBrand> list = brandService.list(wrapper);
        return  Result.success(list);
    }

    @ApiOperation("前台分页查询品牌")
    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(required = false, defaultValue = "") String name,
                              @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                              @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<SBrand> query = Wrappers.<SBrand>lambdaQuery().like(SBrand::getName, name);
        IPage<SBrand> page = brandService.page(new Page<>(pageNum, pageSize), query);
        return Result.success(page);
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        brandService.removeById(id);
        return Result.success();
    }




}
